<?php


namespace App\Http\Rest\Index;

use Framework\Foundation\Cache\RedisCache;
use Framework\Utils\RedisFactory;
use Naroga\RedisCache\Redis;
use youwen\exwechat\ApiClient;
use youwen\exwechat\Request\WebOAuthToken;
use youwen\exwechat\TokenManager;
use Framework\Foundation\Config;

class WeixinController
{
    public function index()
    {
        $this->test();
        exit;
    }

    public function showLink()
    {
    }

    public function test()
    {
        $redis = RedisFactory::create();
//        $redis->set('aaab', "123");
//        $ret = $redis->get('aaab');

        $redisCache = new RedisCache($redis);
        $config = Config::instance()->get('app.wechat');

        $tokenManager = new TokenManager($config, $redisCache);
        $token = $tokenManager->getAccessToken();
        $api = new ApiClient();


//        $ipRequest = (new Ips)->getIps($token);
        $code = WebOAuthToken::getScopeCodeUrl(
            $tokenManager->getConfig()->getAppId(),
            $tokenManager->getConfig()->getRedirectUri()
        );

        $userInfo = WebOAuthToken::getScopeCodeUrl(
            $tokenManager->getConfig()->getAppId(),
            $tokenManager->getConfig()->getRedirectUri(),
            WebOAuthToken::USER_INFO_SCOPE
        );
//        $ret = $api->send($code);


        echo '<pre>';
        print_r($token);
        echo '<br/>';
        echo '<a href="' . $code . '">', "授权", '</a>';
        echo '<br/>';
        echo '<br/>';
        echo '<a href="' . $userInfo . '">', "授权-userinfo", '</a>';
        exit('</pre>');
//        $host = '';
//        $response = ResponseGen::getDefaultResponse();
//        $cookie = new SetCookie(['Name' => 'Authorization', 'Value' => "123", 'Expires' => time() + 86400 * 30]);
//        $response = $response->withHeader('Set-Cookie', $cookie->__toString());
//        $response->withHeader('Location', $host);
    }


    public function callback($request)
    {
        $redis = RedisFactory::create();
//        $redis->set('aaab', "123");
//        $ret = $redis->get('aaab');

        $redisCache = new RedisCache($redis);
        $config = Config::instance()->get('app.wechat');

        $tokenManager = new TokenManager($config, $redisCache);

        $request = WebOAuthToken::getOauthToken($tokenManager->getConfig()->getAppId(), $tokenManager->getConfig()->getSecret(), $_GET['code']);
        $api = new ApiClient();
        $ret = $api->send($request);
        echo '<pre>';
        print_r('callback');
        print_r($ret);
        echo '<br/>';
        echo '<br/>';
        print_r($_GET);
        echo '<br/>';
        print_r($_POST);
        echo '<br/>';
        print_r($request);
        exit('</pre>');
    }
}
